#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl.hpp>
#include <rapidjson/document.h>
#include <iostream>
#include "config.h"
#include "https_connection_pool.h"

bool LighterConfig::init(std::shared_ptr<HttpsConnectionPool>& httpsConnPool) {
    try {
        std::string target = "/api/v1/orderBookDetails";

        // 使用 HttpsConnection 的同步接口获取响应
        std::string response = httpsConnPool->syncSendRequest("GET", target, "", {});

        // 解析 JSON
        rapidjson::Document doc;
        doc.Parse(response.c_str());
        if (doc.HasParseError() || !doc.HasMember("order_book_details")) {
            std::cerr << "JSON parse error" << std::endl;
            return false;
        }

        const auto& arr = doc["order_book_details"];
        if (!arr.IsArray()) return false;

        for (const auto& m : arr.GetArray()) {
            if (!m.HasMember("market_id") || !m.HasMember("symbol")) continue;

            int market_id = m["market_id"].GetInt();
            std::string symbol = m["symbol"].GetString();

            marketIdToSymbol[market_id] = symbol;
            symbolToMarketId[symbol] = market_id;

            MarketInfo info;
            info.taker_fee = m["taker_fee"].GetString();
            info.maker_fee = m["maker_fee"].GetString();
            info.liquidation_fee = m["liquidation_fee"].GetString();
            info.min_base_amount = m["min_base_amount"].GetString();
            info.min_quote_amount = m["min_quote_amount"].GetString();
            info.order_quote_limit = m["order_quote_limit"].GetString();
            info.supported_size_decimals = m["supported_size_decimals"].GetInt();
            info.supported_price_decimals = m["supported_price_decimals"].GetInt();
            info.supported_quote_decimals = m["supported_quote_decimals"].GetInt();
            info.size_decimals = m["size_decimals"].GetInt();
            info.price_decimals = m["price_decimals"].GetInt();

            marketInfoMap[market_id] = info;
        }

        std::cout << "✅ Config 初始化成功，共加载 "
                  << marketIdToSymbol.size() << " 个市场。" << std::endl;

        return true;

    } catch (const std::exception& e) {
        std::cerr << "Error in Config::init(): " << e.what() << std::endl;
        return false;
    }
}

// bool BinanceConfig::init(std::shared_ptr<HttpsConnectionPool>& httpsConnPool) {
    
// }

